<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin: 10px 0"
      @click="showDialog"
    >
      添加
    </el-button>
    <el-table border stripe :data="tradeMarkList" style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="80px">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column label="品牌LOGO" width="width">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.logoUrl"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateTradeMark(row)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeTradeMark(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="pageNum"
      :page-sizes="[3, 5, 10]"
      :page-size="pageSize"
      layout=" prev, pager, next, jumper, ->, sizes, total"
      :total="totalCount"
      style="margin-top: 20px; text-align: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <el-dialog
      :title="formModel.id ? '编辑品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      width="width"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formModel"
        style="width=80%"
        :rules="formRules"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="formModel.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="115px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formModel.logoUrl"
              :src="formModel.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTradeMark"> 确 定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTradeMarkListApi, addTradeMarkApi, updateTradeMarkApi, removeTradeMarkApi } from '@/api/tradeMark'

export default {
  name: 'TradeMark',
  data () {
    return {
      totalCount: 0,
      pageSize: 3,
      pageNum: 1,
      tradeMarkList: [],
      dialogVisible: false,
      formModel: {
        tmName: '',
        logoUrl: ''
      },
      formRules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2-10个字符', trigger: 'change' }
        ],
        logoUrl: [{ required: true, message: '请选择品牌logo', trigger: 'change' }]
      }
    }
  },
  created () {
    this.getTradeMarkList()
  },
  methods: {
    async getTradeMarkList () {
      const { data, code } = await getTradeMarkListApi(this.pageNum, this.pageSize)
      // console.log(data)
      if (code === 200) {
        this.tradeMarkList = data.records
        this.totalCount = data.total
      }
    },
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.pageSize = newSize
      this.getTradeMarkList()
    },
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.pageNum = newPage
      this.getTradeMarkList()
    },
    showDialog () {
      this.dialogVisible = true
    },
    async updateTradeMark (row) {
      console.log(row)
      this.dialogVisible = true
      this.formModel = { ...row }
    },
    handleAvatarSuccess (res, file) {
      // console.log(res, file)
      this.formModel.logoUrl = res.data
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleDialogClose () {
      this.$refs.formRef.resetFields()
      this.formModel = {
        tmName: '',
        logoUrl: ''
      }
    },
    addTradeMark () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return this.$message.error('表单有误')
        if (!this.formModel.id) {
          const result = await addTradeMarkApi(this.formModel)
          // console.log(result)
          if (result.code === 200) {
            this.$message.success('添加品牌成功')
          }
        } else {
          const result = await updateTradeMarkApi(this.formModel)
          console.log(result)
          this.$message.success('编辑品牌成功')
        }
        this.dialogVisible = false
        this.getTradeMarkList()
      })
    },
    async removeTradeMark (row) {
      try {
        await this.$confirm(`确认要删除 ${row.tmName} 吗?`, '提示')
        await removeTradeMarkApi(row.id)
        const newPage = Math.ceil((this.totalCount - 1) / this.pageSize)
        if (newPage < this.pageNum) this.pageNum = newPage
        this.$message.success('删除成功')
        this.getTradeMarkList()
      } catch (error) {
        console.log(error)
        this.$message.info('取消了删除')
      }
    }
  }
}
</script>

<style lang="scss">
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
